package main

import (
	"log"
	"smart-weekly-report/app/server"
	"smart-weekly-report/config"
	"time"
)

// 启动定时任务
func startCronJobs() {
	// 每周五下午自动生成周报
	ticker := time.NewTicker(24 * time.Hour)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			now := time.Now()
			if now.Weekday() == time.Friday && now.Hour() == 17 {
				generateAutoReport()
			}
		}
	}
}

// 自动生成周报
func generateAutoReport() {
	_, week := time.Now().ISOWeek()

	gitService := server.NewGitService(config.Config{}.GitRepoPath)
	commits, err := gitService.GetCommitsByWeek(week)
	if err != nil {
		log.Printf("自动生成周报失败: %v", err)
		return
	}

	genkitService := server.NewGenkitService(config.Config{}.GenkitAPIKey)
	content, err := genkitService.GenerateReportContent(commits)
	if err != nil {
		log.Printf("AI生成周报内容失败: %v", err)
		return
	}

	report := server.WeeklyReport{
		Week:        week,
		Content:     content,
		GeneratedAt: time.Now(),
		Sent:        false,
	}

	config.Db.Create(&report)

	// 自动发送到飞书
	feishuService := server.NewFeishuService(config.Config{}.FeishuWebhook)
	err = feishuService.SendWeeklyReport(&report)
	if err != nil {
		return
	}

	log.Printf("第%d周周报自动生成并发送完成", week)
}
